package com.qzsoft.zhjd.machine.zhgcloud.worktime;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qzsoft.zhjd.machine.modules.machinedaily.entity.MachineDailyEntity;
import com.qzsoft.zhjd.machine.modules.machinedaily.entity.MachineDailyWorkrecordsEntity;
import com.qzsoft.zhjd.machine.modules.machinedaily.service.MachineDailyService;
import com.qzsoft.zhjd.machine.modules.machineinfo.entity.MachineInfoEntity;
import com.qzsoft.zhjd.machine.modules.machineinfo.service.MachineInfoService;
import com.qzsoft.zhjd.machine.zhgcloud.ZhgHandler;
import com.qzsoft.zhjd.machine.zhgcloud.ZhgResultDataCallback;
import com.qzsoft.zhjd.machine.zhgcloud.fuel.ZhgFuelHandler;
import com.qzsoft.zhjd.machine.zhgcloud.worktime.model.ZhgFuelConsumeModel;
import com.qzsoft.zhjd.machine.zhgcloud.worktime.model.ZhgWorktimeModel;

/**
 * @ClassName ZhgWorktimeHandler
 * @Description 机械设备工时数据处理
 * @author linhuawei
 * @since 2021-11-04
 */
@Component
public class ZhgWorktimeHandler {

    @Value("${zhgcloud.urls.workTime}")
    private String workTimeUrl;

    @Autowired
    private ZhgHandler zhgHandler;

    @Autowired
    private ZhgFuelHandler zhgFuelHandler;

    @Autowired
    private MachineDailyService machineDailyService;

    @Autowired
    private MachineInfoService machineInfoService;

    /**
     * @Title worktime
     * @Description 获取指定日期工时
     * @param machineList 设备列表
     * @param reportDate  日期
     */
    // @Async
    public void worktime(Date reportDate) {
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String reportDateStr = sdf.format(reportDate);
        
        // 获取油耗信息
        List<ZhgFuelConsumeModel> fuelConsumeList = zhgFuelHandler.getfuelConsumeList(reportDateStr);
        Map<String, BigDecimal> fuelConsumeMap = new HashMap<String, BigDecimal>();
        if (ObjectUtils.isNotEmpty(fuelConsumeList)) {
            fuelConsumeList.forEach(item -> {
                if (null != item.getOil()) {
                    fuelConsumeMap.put(item.getMachine_key(), item.getOil());
                }
            });
        }
        
        // 获取设备列表
        QueryWrapper<MachineInfoEntity> queryWrapper = new QueryWrapper<MachineInfoEntity>();
        queryWrapper.select("id", "machine_key", "taiban_hour");
        List<MachineInfoEntity> machineList = machineInfoService.list(queryWrapper);
        
        // 设置查询条件
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("date", reportDateStr);

        // 获取每个设备工时数据、
        ZhgResultDataCallback callback = (JSONObject resultJson) -> {
            return resultJson.getString("daily_report");
        };
        ZhgWorktimeModel worktimeModel;
        MachineDailyEntity entity;
        for (MachineInfoEntity item : machineList) {
            if (ObjectUtils.isNotEmpty(item.getMachineKey())) {
                params.put("machine_key", item.getMachineKey());
                worktimeModel = zhgHandler.httpGetObject(workTimeUrl, params, ZhgWorktimeModel.class, callback);

                // 获取设备油耗
                BigDecimal fuelConsume = fuelConsumeMap.get(item.getMachineKey());

                // 处理数据
                entity = cover(item, worktimeModel, fuelConsume);
                if (null != entity) {
                    machineDailyService.save(entity, reportDate);
                }
            }
        }
    }

    /**
     * @Title cover
     * @Description 数据对象转化
     * @param infoEntity    设备信息
     * @param worktimeModel 工时信息
     * @param fuelConsume   油耗信息
     * @return 转化后数据
     */
    private MachineDailyEntity cover(MachineInfoEntity infoEntity, ZhgWorktimeModel worktimeModel,
            BigDecimal fuelConsume) {
        // 如果工时信息无效，不做处理
        if (null == worktimeModel || !worktimeModel.isValid()) {
            return null;
        }

        // 获取工时、里程数据
        long workTime = null == worktimeModel.getWork_time() ? 0L : worktimeModel.getWork_time();
        long idleTime = null == worktimeModel.getIdle_time() ? 0L : worktimeModel.getIdle_time();
        long offTime = null == worktimeModel.getOff_time() ? 0L : worktimeModel.getOff_time();
        long mileage = null == worktimeModel.getMileage() ? 0L : worktimeModel.getMileage();
        long effectiveTime = workTime + idleTime;
        fuelConsume = null == fuelConsume ? BigDecimal.ZERO : fuelConsume;

        // 处理数据
        MachineDailyEntity entity = new MachineDailyEntity();
        entity.setMachineId(infoEntity.getId());
        entity.setMachineKey(infoEntity.getMachineKey());
        entity.setWorkTime(workTime);
        entity.setIdleTime(idleTime);
        entity.setOffTime(offTime);
        entity.setEffectiveTime(effectiveTime);
        entity.setMileage(mileage);
        entity.setFuelConsume(fuelConsume);

        // 计算台班数（8小时一台班）
        BigDecimal taiban = new BigDecimal(effectiveTime);
        taiban = taiban.divide(new BigDecimal(8 * 60 * 60), 2, RoundingMode.HALF_UP);
        entity.setTaiban(taiban);
//        if (null != infoEntity.getTaibanHour()) {
//            BigDecimal taiban = new BigDecimal(effectiveTime);
//            taiban = taiban.divide(new BigDecimal(infoEntity.getTaibanHour() * 60 * 60), 2, RoundingMode.HALF_UP);
//            entity.setTaiban(taiban);
//            entity.setTaibanHour(infoEntity.getTaibanHour());
//        }

        // 百公里油耗 = 油耗 / (里程_单位米 / (100 * 1000))
        // = (油耗 * 100 * 1000) / 里程_单位米
        // = (油耗 * 100000) / 里程_单位米
        BigDecimal fuelConsumeMileage = BigDecimal.ZERO;
        if (0L != mileage) {
            fuelConsumeMileage = fuelConsume.multiply(new BigDecimal(100000)).divide(new BigDecimal(mileage), 2,
                    RoundingMode.HALF_UP);
        }
        entity.setFuelConsumeMileage(fuelConsumeMileage);

        // 小时油耗 = 油耗 / ((工作时长_单位秒 + 怠速时长_单位秒) / (60 * 60))
        // = (油耗 * 60 * 60) / (工作时长_单位秒 + 怠速时长_单位秒)
        // = (油耗 * 3600) / (工作时长_单位秒 + 怠速时长_单位秒)
        long time = workTime + idleTime;
        BigDecimal fuelConsumeTime = BigDecimal.ZERO;
        if (0L != time) {
            fuelConsumeTime = fuelConsume.multiply(new BigDecimal(3600)).divide(new BigDecimal(time), 2,
                    RoundingMode.HALF_UP);
        }
        entity.setFuelConsumeTime(fuelConsumeTime);

        // 获取工时记录
        if (ObjectUtils.isNotEmpty(worktimeModel.getWork_records())) {
            List<MachineDailyWorkrecordsEntity> workrecords = new ArrayList<MachineDailyWorkrecordsEntity>();
            worktimeModel.getWork_records().forEach(item -> {
                MachineDailyWorkrecordsEntity temp = new MachineDailyWorkrecordsEntity();
                temp.setMachineId(infoEntity.getId());
                temp.setMachineKey(infoEntity.getMachineKey());
                if (null != item.getTime() && 2 == item.getTime().length) {
                    temp.setStartTime(item.getTime()[0]);
                    temp.setEndTime(item.getTime()[1]);
                    
                    long duration = (temp.getEndTime().getTime() - temp.getStartTime().getTime()) / 1000;
                    temp.setDuration(duration);
                }
                if (null != item.getRange() && 2 == item.getRange().length) {
                    temp.setStartRang(item.getRange()[0]);
                    temp.setEndRang(item.getRange()[1]);
                }
                temp.setState(item.getState());
                workrecords.add(temp);
            });
            entity.setWorkrecords(workrecords);
        }

        return entity;
    }

}
